import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:fake_handwriting/Util.dart';
import 'package:fake_handwriting/generated/l10n.dart';
import 'package:fake_handwriting/http/bean/file_bean.dart';
import 'package:fake_handwriting/http/bean/upload_bean.dart';
import 'package:fake_handwriting/http/http.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:image_preview/image_preview.dart';
class Create extends StatefulWidget {
  const Create({Key? key}) : super(key: key);
  @override
  CreatePage createState() => CreatePage();
}
class ListBean {
  String title;
  Icon icon;
  Widget desc;
  ListBean(this.title, this.icon, this.desc);
}
class CreatePage extends State<Create> {
  List<ListBean> list = [];
  Color fontColor = Colors.black;
  UploadBean? uploadImageBean;
  UploadBean? uploadFontBean;
  int fontDownloadProcess=0;
  List<CancelToken> tokens=[];
  String content="";
  int fontSize=48;
  int fontCount=22;
  double rowSpacing=9.8;
  int startX=160;
  int startY=90;
  int lines=26;
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero).then((value){
      list.addAll([
        ListBean(S.of(context).background, const Icon(Icons.picture_in_picture_alt_outlined), Text(S.of(context).notSelected,style: const TextStyle(fontSize: 20),)),
        ListBean(S.of(context).word, const Icon(Icons.font_download), Text(S.of(context).notEdited,style: const TextStyle(fontSize: 20),)),
        ListBean(S.of(context).font, const Icon(Icons.perm_device_information), Text(S.of(context).notSelected,style: const TextStyle(fontSize: 20),)),
        ListBean(S.of(context).fontSize, const Icon(Icons.format_size), const Text("48",style: TextStyle(fontSize: 20),)),
        ListBean(S.of(context).wordsPerLine, const Icon(Icons.format_size), const Text("22",style: TextStyle(fontSize: 20),)),
        ListBean(S.of(context).fontColor, const Icon(Icons.format_color_text), const CircleAvatar(backgroundColor: Colors.black)),
        ListBean(S.of(context).rowSpacing, const Icon(Icons.format_align_justify_outlined), const Text("9.8",style: TextStyle(fontSize: 20),)),
        ListBean(S.of(context).paddingLeft, const Icon(Icons.align_horizontal_left), const Text("160",style: TextStyle(fontSize: 20),)),
        ListBean(S.of(context).paddingTop, const Icon(Icons.align_vertical_top), const Text("90",style: TextStyle(fontSize: 20),)),
        ListBean(S.of(context).numberOfRows, const Icon(Icons.align_vertical_bottom), const Text("26",style: TextStyle(fontSize: 20),)),
        ListBean(S.of(context).reset, const Icon(Icons.align_vertical_bottom), Text(S.of(context).reset,style: const TextStyle(fontSize: 20),)),
      ]);
      setState(() {});
    });
  }
  @override
  void dispose() {
    for (var element in tokens) {
      element.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(S.of(context).create),
          actions: [
            IconButton(
              icon: const Icon(Icons.preview),
              tooltip: S.of(context).preview,
              onPressed: () async {
                if(uploadImageBean==null||uploadImageBean!.path==null){
                  Util.toast(S.of(context).selectABackgroundPicture);
                  return;
                }
                if(content.isEmpty){
                  Util.toast(S.of(context).pleaseEditTheText);
                  return;
                }
                if(uploadFontBean==null){
                  Util.toast(S.of(context).pleaseSelectAFont);
                  return;
                }
                String url=await Http.make(
                    title: "",
                    image_id: '${uploadImageBean!.id}',
                    content: content,

                    font_id: '${uploadFontBean!.id}',
                    fontSize: '$fontSize',
                    fontCount: '$fontCount',

                    fontColor:"#${fontColor.value.toRadixString(16).substring(2)}",
                    rowSpacing: '$rowSpacing',

                    start_x: '$startX',
                    start_y: '$startY',
                    line: '$lines',
                    type: "preview"
                );
                List<String> urlList=[];
                for (var element in List<String>.from(jsonDecode(url))) {
                  urlList.add("${Http.BASE_URL}$element?timestamp="+DateTime.now().millisecondsSinceEpoch.toString());
                }
                openImagesPage(
                  Navigator.of(context),
                  imgUrls:urlList,
                );
              },
            ),
            IconButton(
              icon: const Icon(Icons.done),
              tooltip: S.of(context).finish,
              onPressed: () async {
                if(uploadImageBean==null||uploadImageBean!.path==null){
                  Util.toast(S.of(context).selectABackgroundPicture);
                  return;
                }
                if(content.isEmpty){
                  Util.toast(S.of(context).pleaseEditTheText);
                  return;
                }
                if(uploadFontBean==null){
                  Util.toast(S.of(context).pleaseSelectAFont);
                  return;
                }
                var _textController=TextEditingController();
                var res=await showDialog(context: context, builder:(c)=>SimpleDialog(
                  title: Text(S.of(context).tips),
                  children: [
                    TextField(
                      controller: _textController,
                      decoration: InputDecoration(
                          hintText: S.of(context).pleaseNameYourWork
                      ),
                    ),
                    Row(children: [
                      ElevatedButton(onPressed:(){
                        Navigator.pop(context);
                      }, child:Text(S.of(context).cancel)), ElevatedButton(onPressed:(){
                        Navigator.pop(context,_textController.text);
                      }, child:Text(S.of(context).save)),
                    ],mainAxisAlignment: MainAxisAlignment.spaceAround,)
                  ],
                ));
                if(res!=null&&res.isNotEmpty){
                  try{
                    await Http.make(
                        title: res,
                        image_id: '${uploadImageBean!.id}',
                        content: content,
                        font_id: '${uploadFontBean!.id}',
                        fontSize: '$fontSize',
                        fontCount: '$fontCount',
                        fontColor:"#${fontColor.value.toRadixString(16).substring(2)}",
                        rowSpacing: '$rowSpacing',
                        start_x: '$startX',
                        start_y: '$startY',
                        line: '$lines',
                        type: "done"
                    );
                    Util.toast(S.of(context).saveSucceed);
                    Navigator.pop(context);
                  }catch(e){
                  }
                }
              },
            ),
          ],
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 20),
          child: GridView.builder(
              shrinkWrap: true,
              gridDelegate:
              const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  crossAxisSpacing: 5,
                  mainAxisSpacing: 5,
                  childAspectRatio: 1),
              itemCount: list.length,
              itemBuilder: (BuildContext context, int index) {
                return InkWell(
                  onTap: () async {
                    var title=list[index].title;
                    if(title==S.of(context).background){
                      var res = await showDialog(context: context, builder: (context) => SimpleDialog(
                        title: Text(S.of(context).selectABackgroundPicture),
                        children: <Widget>[
                          SimpleDialogOption(
                            child:Text(S.of(context).uploadBackgroundAndUse),
                            onPressed: () {
                              Navigator.pop(context, S.of(context).uploadBackgroundAndUse);
                            },
                          ),
                          const Divider(),
                          SimpleDialogOption(
                            child:Text(S.of(context).selectOnlineBackground),
                            onPressed: () {
                              Navigator.pop(
                                  context,S.of(context).selectOnlineBackground);
                            },
                          ),
                        ],
                      ));
                      if (res == S.of(context).uploadBackgroundAndUse) {
                        FilePickerResult? result = await FilePicker.platform.pickFiles(type: FileType.image, allowCompression: false);
                        if (result != null) {
                          Util.showLoading(context);
                          uploadImageBean = await Http.upload(result.files.single.path.toString(), result.files.single.name, "images");
                          list[index].desc = Text(S.of(context).reselection,style: const TextStyle(fontSize: 20));
                          Navigator.pop(context);
                          setState(() {});
                        }
                      } else if(res ==S.of(context).selectOnlineBackground){
                        Navigator.pushNamed(
                            context, "online_image",
                            arguments: "choose").then((value) {
                          if (value != null&&value.runtimeType==FileBean) {
                            FileBean bean = value as FileBean;
                            uploadImageBean=UploadBean(id: int.parse(bean.id.toString()),path: bean.path,email: "",name: bean.filename,filetype:"");
                            list[index].desc = Text(S.of(context).reselection,style: const TextStyle(fontSize: 20));
                            setState(() {});
                          }
                        });
                      }
                    }
                    if(title==S.of(context).word){
                      Navigator.pushNamed(context, "input_text",arguments: content).then((value) {
                        content=value.toString().replaceAll("null","");
                        if(content==""){
                          list[index].desc = Text(S.of(context).notEdited, style: const TextStyle(fontSize: 20),);
                        }else {
                          list[index].desc = Text(S.of(context).reEdit, style: const TextStyle(fontSize: 20),);
                        }
                        setState((){});
                      });
                    }
                    if(title==S.of(context).font){
                      var res = await showDialog(context: context, builder: (context) => SimpleDialog(
                        title: Text(S.of(context).selectText),
                        children: <Widget>[
                          SimpleDialogOption(
                            child: Text(S.of(context).uploadTextAndUse),
                            onPressed: () {
                              Navigator.pop(
                                  context, S.of(context).uploadTextAndUse);
                            },
                          ),
                          const Divider(),
                          SimpleDialogOption(
                            child: Text(S.of(context).selectOnlineText),
                            onPressed: () {
                              Navigator.pop(context,S.of(context).selectOnlineText);
                            },
                          ),
                        ],
                      ));
                      if (res == S.of(context).uploadTextAndUse) {
                        FilePickerResult? result =
                        await FilePicker.platform.pickFiles();
                        if (result != null) {
                          Util.showLoading(context);
                          uploadFontBean = await Http.upload(result.files.single.path.toString(), result.files.single.name, 'font');
                          list[index].desc = Text(S.of(context).reselection);
                          Navigator.pop(context);
                          setState(() {});
                          loadFont();
                        }
                      } else if(res==S.of(context).selectOnlineText){
                        Navigator.pushNamed(context, "online_font", arguments: "choose").then((value) {
                          if (value != null&&value.runtimeType==FileBean) {
                            FileBean bean=value as FileBean;
                            uploadFontBean =UploadBean(path: bean.path,filetype: "",name: bean.filename,id: int.parse(bean.id.toString()));
                            list[index].desc = Text(S.of(context).reselection);
                            setState(() {});
                            loadFont();
                          }
                        });
                      }
                    }
                    if(title==S.of(context).fontSize){
                      Util.showInputNumberDialog(context,fontSize,(b,i){
                        if(!b){
                          fontSize=i;
                          list[index].desc=Text("$fontSize",style: const TextStyle(fontSize: 20),);
                          setState(() {});
                        }
                      });
                    }
                    if(title==S.of(context).wordsPerLine){
                      Util.showInputNumberDialog(context,fontCount,(b,i){
                        if(!b){
                          fontCount=i;
                          list[index].desc=Text("$fontCount",style: const TextStyle(fontSize: 20),);
                          setState(() {});
                        }
                      });
                    }
                    if(title==S.of(context).rowSpacing){
                      Util.showInputNumberDialog(context,rowSpacing,(b,i){
                        if(!b){
                          rowSpacing=double.parse("$i");
                          list[index].desc=Text("$rowSpacing",style: const TextStyle(fontSize: 20),);
                          setState(() {});
                        }
                      });
                    }
                    if(title==S.of(context).paddingLeft){
                      Util.showInputNumberDialog(context,startX,(b,i){
                        if(!b){
                          startX=i;
                          list[index].desc=Text("$startX",style: const TextStyle(fontSize: 20),);
                          setState(() {});
                        }
                      });
                    }
                    if(title==S.of(context).paddingTop){
                      Util.showInputNumberDialog(context,startY,(b,i){
                        if(!b){
                          startY=i;
                          list[index].desc=Text("$startY",style: const TextStyle(fontSize: 20),);
                          setState(() {});
                        }
                      });
                    }
                    if(title==S.of(context).numberOfRows){
                      Util.showInputNumberDialog(context,lines,(b,i){
                        if(!b){
                          lines=i;
                          list[index].desc=Text("$lines",style: const TextStyle(fontSize: 20),);
                          setState(() {});
                        }
                      });
                    }
                    if(title==S.of(context).reset){
                      uploadImageBean = null;
                      content="";
                      uploadFontBean = null;
                      list[0].desc = Text(S.of(context).notSelected,style: const TextStyle(fontSize: 20),);
                      list[1].desc = Text(S.of(context).notEdited,style: const TextStyle(fontSize: 20),);
                      list[2].desc = Text(S.of(context).notSelected,style: const TextStyle(fontSize: 20),);

                      list[3].desc = const Text("48",style: TextStyle(fontSize: 20),);
                      fontSize=48;

                      list[4].desc = const Text("22",style: TextStyle(fontSize: 20),);
                      fontCount=22;

                      fontColor=Colors.black;
                      list[5].desc=CircleAvatar(backgroundColor:fontColor);

                      list[6].desc = const Text("9.8",style: TextStyle(fontSize: 20),);
                      rowSpacing=9.8;//行间距

                      list[7].desc = const Text("160",style: TextStyle(fontSize: 20),);
                      startX=160;

                      list[8].desc = const Text("90",style: TextStyle(fontSize: 20),);
                      startY=90;

                      list[9].desc = const Text("26",style: TextStyle(fontSize: 20),);
                      lines=26;

                      setState(() {});
                    }
                    if(title==S.of(context).fontColor){
                      showDialog(
                        context: context,
                        builder:(c)=>AlertDialog(
                          title: const Text('选择字体颜色'),
                          content: SingleChildScrollView(
                            child: MaterialPicker(
                              pickerColor: Colors.black,
                              onColorChanged:(_color){
                                setState(() {
                                  fontColor=_color;
                                  list[index].desc=CircleAvatar(backgroundColor:fontColor);
                                });
                              },
                            ),
                          ),
                          actions: <Widget>[
                            ElevatedButton(
                              child: const Text('确定'),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ],
                        ),
                      );
                    }
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(
                          color: Colors.blue
                      ),
                    ),
                    child: Stack(
                      children: [
                        (list[index].title==S.of(context).background&&uploadImageBean!=null)?Container(
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: NetworkImage(Http.BASE_URL+uploadImageBean!.path!)
                              )
                          ),
                        ):Container(),
                        Column(
                          children: [
                            (index==2&&uploadFontBean!=null)?(
                                (fontDownloadProcess!=100)? Text("${S.of(context).downloading}:$fontDownloadProcess%",style: const TextStyle(fontSize: 20),):
                                Text(S.of(context).selected,style: TextStyle(fontSize: 20,fontFamily: "family_${uploadFontBean!.id}"))
                            ): list[index].desc,
                            const SizedBox(
                              height: 5,
                            ),
                            IntrinsicHeight(
                              child: Wrap(
                                  alignment: WrapAlignment.center,
                                  children: [
                                    list[index].icon,
                                    Center(child: Text(list[index].title)),
                                  ]
                              ),
                            ),
                          ],
                          mainAxisAlignment: MainAxisAlignment.center,
                        ),
                      ],
                    ),
                  ),
                );
              }),
        ));
  }
  Future<void> loadFont() async {
    fontDownloadProcess = 0;
    String dir = await Util.getCacheDir();
    var file = File("$dir${uploadFontBean!.id}${uploadFontBean!.name}");
    if (await file.exists()) {
      fontDownloadProcess = 100;
      var fontLoader = FontLoader("family_${uploadFontBean!.id}");
      fontLoader.addFont(Util.getByteData(file));
      await fontLoader.load();
      setState(() {});
    } else {
      CancelToken token=CancelToken();
      tokens.add(token);
      await Dio().download(
          Http.BASE_URL + uploadFontBean!.path!, "$dir${uploadFontBean!.id}${uploadFontBean!.name}",
          onReceiveProgress: (a, b) async {
            fontDownloadProcess = ((a / b) * 100).toInt();
            setState(() {});
            if (fontDownloadProcess == 100) {
              //下载完开始加载
              File? file = File("$dir${uploadFontBean!.id}${uploadFontBean!.name}");
              var fontLoader = FontLoader("family_${uploadFontBean!.id}");
              fontLoader.addFont(Util.getByteData(file));
              await fontLoader.load();
              setState(() {});
            }
          },cancelToken: token
      );
    }
  }
}